package com.eascs.archive.controller.credit;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.backfee.controller.O2oBondFeeController;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.afterloan.controller.O2oAfterLoanController;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.form.ArchivequeryForm;
import com.eascs.archive.service.ArchiveRecordService;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.text.Format;
import java.util.List;


@Controller
public class ArchiveQueryController extends BaseMasterViewController {
	
	private final Logger logger = LoggerFactory.getLogger(ArchiveQueryController.class);

	@Autowired
	private ArchiveRecordService archiveRecordService;

	@Reference
	SysOrgService sysOrgService;

	@Override
	public void preHandle() {
		super.preHandle();
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "CreditA");
	}

	@RequestMapping("/archive/query")
	public String archiveCreditQuery(ArchivequeryForm entity) {
		String reporto2ourl = "/archive/credit/download";
		String url          = "/archive/query";
		

		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		
		//获取报表查询的地址源
		if (entity != null) {
			String LoanapplyNo = entity.getBillCode() == null ? "" : entity.getBillCode();
			url = UrlUtil.appendUrl(url, "billCode", LoanapplyNo);
			String CreditStartDate = entity.getCreditStartDate() == null ? "" : entity.getCreditStartDate();
			url = UrlUtil.appendUrl(url, "CreditStartDate", CreditStartDate);
			String CreditEndDate = entity.getCreditEndDate() == null ? "" : entity.getCreditEndDate();
			url = UrlUtil.appendUrl(url, "CreditEndDate", CreditEndDate);
			String UserFullName = entity.getUserFullName() == null ? "" : entity.getUserFullName();
			url = UrlUtil.appendUrl(url, "UserFullName", UserFullName);

			if (StringUtil.isNotBlank(entity.getCreditBankLoan())) {
				url = UrlUtil.appendUrl(url, "creditBankLoan", entity.getCreditBankLoan());
			}
			if (StringUtil.isNotBlank(entity.getHostProvince())) {
				url = UrlUtil.appendUrl(url, "hostProvince", entity.getHostProvince());
			}
			url = url + "&o2oIndex=";
		} else {
			url = url + "?o2oIndex=";
		}
		PageResult<Object[]> pageResult        = archiveRecordService.queryNewCreditArchive(entity);
		String               titles[]          = {"贷款单号", "征信时间", "省区", "征信银行", "平台", "客户类型", "姓名", "身份证号", "归档状态", "流程状态", "经办人"};
		SelectDataOption[]   selectDataOptions = {null, null, null, null, null, new SelectDataOption("USER_RELATIONSHIP"), null, null,new SelectDataOption("CREDIT_FILE_TYPE"), new SelectDataOption("CREDIT_WF_STATUS"), null};
		PaginationInfo       o2oPagingInfo     = new PaginationInfo(pageResult, titles, url);
		o2oPagingInfo.setBuildPagingNavigation(true);
		Button[] titleButton = new Button[]{ButtonHelper.createAjaxButton(null, "/archive/attachmentQuery?id={0}")};
		Button   more        = ButtonHelper.createAjaxButton("启动流程", "/archive/startUpFile?id={0}", "CREDIT_FILE");
		more.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object arg0) {
				Object[] param = (Object[]) arg0;
				if (param[10].equals(StatusContexts.ZXGD_NEW)) {
					return true;
				}
				return false;
			}
		});
		o2oPagingInfo.setMoreButtons(new Button[]{more});
		o2oPagingInfo.setTitleButtons(titleButton);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFormats(new Format[]{null, null, null, null, null, null, null, null, null, null, null, null});
		ViewContext.put("vo", entity);
		ViewContext.put("paginationInfo", o2oPagingInfo);

		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "archive/credit/archive_query_view";
	}

	@RequestMapping("/archive/credit/download")
	public void dowanload(ArchivequeryForm entity, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		entity.setPageSize(8000);
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		PageResult<Object[]> pageResult = archiveRecordService.queryNewCreditArchiveDownloadData(entity);
		String               path       = O2oAfterLoanController.class.getResource("/excelTemplate").getPath();
		StringBuffer         s          = new StringBuffer();
		String               outPath    = s.append(path).append("/archive-credit.xls").toString();
		OutputStream         os         = null;

		try {
			String outfile   = "征信归档数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes     = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();

			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");

			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oAfterLoanController.class.getResourceAsStream("/excelTemplate/archive-credit.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
			os.close();
		} catch (Exception e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
}
		
	


